// 增强版AI智能推荐引擎
// 更自然的话术和更智能的推荐算法

class EnhancedAIRecommendationEngine {
    constructor() {
        this.db = new Database();
        this.userBehavior = this.loadUserBehavior();
        this.recommendationHistory = this.loadRecommendationHistory();
        this.weatherCache = null;
        this.weatherCacheTime = null;
        this.weatherCacheDuration = 30 * 60 * 1000; // 30分钟缓存
        
        // 初始化AI人格
        this.aiPersonality = {
            name: "小智",
            style: "friendly",
            expertise: "美食推荐专家",
            traits: ["专业", "贴心", "幽默", "细心"]
        };
        
        // 推荐理由模板库
        this.reasonTemplates = this.initReasonTemplates();
        
        // 用户画像标签
        this.userProfiles = this.initUserProfiles();
    }

    // 初始化推荐理由模板
    initReasonTemplates() {
        return {
            // 时间相关推荐理由
            time: {
                morning: [
                    "🌅 早上好！为您推荐营养丰富的早餐，开启美好一天",
                    "☀️ 清晨时光，来一份暖胃的早餐吧",
                    "🌞 一日之计在于晨，营养早餐不能少",
                    "🥣 早上来点热腾腾的，精神一整天"
                ],
                lunch: [
                    "🍽️ 午餐时间到！为您精选营养搭配的午餐",
                    "🥢 中午来点实在的，下午工作有精神",
                    "🍜 午餐推荐，营养均衡，口感丰富",
                    "🍱 中午时光，来份美味的午餐吧"
                ],
                afternoon: [
                    "☕ 下午茶时光，来点小食提提神",
                    "🍰 午后时光，来份精致的下午茶",
                    "🥤 下午来点清爽的，继续加油",
                    "🍪 下午茶推荐，放松一下心情"
                ],
                dinner: [
                    "🌆 晚餐时间，来份丰盛的正餐",
                    "🍽️ 晚上来点好的，犒劳一下自己",
                    "🥘 晚餐推荐，营养丰富，口感绝佳",
                    "🍲 晚上时光，来份温暖的正餐"
                ],
                night: [
                    "🌙 夜宵时间，来点小食解解馋",
                    "🍢 深夜时光，来份热腾腾的夜宵",
                    "🍜 晚上饿了？来份暖胃的夜宵",
                    "🥟 夜宵推荐，满足您的深夜味蕾"
                ]
            },
            
            // 天气相关推荐理由
            weather: {
                sunny: [
                    "☀️ 阳光明媚，推荐清爽解腻的美食",
                    "🌞 好天气配好心情，来份清爽的菜品",
                    "☀️ 阳光正好，来点清爽的提提神",
                    "🌅 天气不错，推荐清爽开胃的美食"
                ],
                rainy: [
                    "🌧️ 雨天湿润，来份热汤暖暖身",
                    "☔ 下雨天最适合来点热腾腾的",
                    "🌧️ 雨天推荐暖身美食，驱散寒意",
                    "☔ 下雨天来点热汤，温暖整个身心"
                ],
                cloudy: [
                    "☁️ 多云天气，来份家常菜最合适",
                    "🌤️ 天气温和，推荐经典家常菜",
                    "☁️ 多云天，来份传统美食吧",
                    "🌤️ 天气不错，推荐经典菜品"
                ],
                hot: [
                    "🔥 天气炎热，推荐清凉解暑的美食",
                    "🌡️ 高温天气，来点清爽的降降温",
                    "🔥 热天推荐清凉美食，消暑解腻",
                    "🌡️ 天气炎热，来份清凉的提提神"
                ],
                cold: [
                    "❄️ 天气寒冷，推荐温补暖身的美食",
                    "🥶 冷天来点热腾腾的，暖暖胃",
                    "❄️ 寒冷天气，推荐暖身美食",
                    "🥶 冷天推荐热食，驱散寒意"
                ]
            },
            
            // 季节相关推荐理由
            season: {
                spring: [
                    "🌸 春暖花开，推荐清淡新鲜的美食",
                    "🌱 春季养生，来份清淡的菜品",
                    "🌸 春天来了，推荐新鲜时令菜",
                    "🌿 春季推荐，清淡养生好选择"
                ],
                summer: [
                    "☀️ 夏日炎炎，推荐清凉解暑的美食",
                    "🌞 夏天来了，来点清爽的降降温",
                    "☀️ 夏日推荐清凉美食，消暑解腻",
                    "🌞 夏天来点清爽的，心情也清爽"
                ],
                autumn: [
                    "🍂 秋高气爽，推荐温补润燥的美食",
                    "🍁 秋天来了，来份温补的养生菜",
                    "🍂 秋季推荐温补美食，润燥养生",
                    "🍁 秋天来点温补的，身体更健康"
                ],
                winter: [
                    "❄️ 冬日寒冷，推荐温补暖身的美食",
                    "⛄ 冬天来了，来点热腾腾的暖暖胃",
                    "❄️ 冬季推荐暖身美食，驱散寒意",
                    "⛄ 冬天来点温补的，身体更暖和"
                ]
            },
            
            // 用户偏好相关推荐理由
            preference: {
                spicy: [
                    "🌶️ 根据您的口味偏好，推荐香辣美食",
                    "🔥 您喜欢辣味，为您精选香辣菜品",
                    "🌶️ 辣味爱好者，推荐正宗川菜",
                    "🔥 香辣美食，满足您的味蕾"
                ],
                sweet: [
                    "🍯 您喜欢甜味，推荐香甜可口的菜品",
                    "🍰 甜食爱好者，为您精选甜品",
                    "🍯 香甜美食，满足您的甜味需求",
                    "🍰 甜味推荐，让心情更甜蜜"
                ],
                healthy: [
                    "🥗 健康生活，推荐营养均衡的菜品",
                    "🥕 养生达人，为您精选健康美食",
                    "🥗 健康推荐，营养搭配更均衡",
                    "🥕 养生美食，让身体更健康"
                ],
                budget: [
                    "💰 性价比之选，美味又实惠",
                    "💵 经济实惠，推荐高性价比菜品",
                    "💰 实惠推荐，好吃不贵",
                    "💵 性价比高，推荐经济实惠的菜品"
                ]
            },
            
            // 菜品特色推荐理由
            dish: {
                popular: [
                    "🔥 人气爆款，大家都爱点",
                    "⭐ 热销菜品，口碑极佳",
                    "🏆 招牌推荐，必点美食",
                    "💯 爆款菜品，人气之选"
                ],
                new: [
                    "🆕 新品上市，尝鲜必选",
                    "✨ 新鲜出炉，推荐尝试",
                    "🆕 新品推荐，抢先体验",
                    "✨ 新口味，值得一试"
                ],
                discount: [
                    "🎉 限时优惠，错过可惜",
                    "💰 特价推荐，超值享受",
                    "🎁 优惠活动，性价比超高",
                    "💸 折扣菜品，实惠之选"
                ],
                high_rating: [
                    "⭐ 高评分菜品，口碑保证",
                    "🏆 好评如潮，推荐尝试",
                    "⭐ 用户好评，品质保证",
                    "🏆 口碑推荐，值得信赖"
                ]
            }
        };
    }

    // 初始化用户画像
    initUserProfiles() {
        return {
            newbie: {
                name: "新手用户",
                description: "刚注册的新用户，推荐热门和经典菜品",
                preferences: ["popular", "classic", "safe"]
            },
            foodie: {
                name: "美食达人",
                description: "对美食有独特见解，推荐创新和特色菜品",
                preferences: ["innovative", "unique", "trendy"]
            },
            health_conscious: {
                name: "健康达人",
                description: "注重健康饮食，推荐营养均衡的菜品",
                preferences: ["healthy", "nutritious", "organic"]
            },
            budget_conscious: {
                name: "经济实用型",
                description: "注重性价比，推荐实惠美味的菜品",
                preferences: ["budget", "value", "affordable"]
            },
            adventurous: {
                name: "冒险型用户",
                description: "喜欢尝试新口味，推荐特色和异国菜品",
                preferences: ["exotic", "spicy", "unique"]
            }
        };
    }

    // 获取用户画像
    getUserProfile(userId) {
        const userBehavior = this.getUserBehavior(userId);
        if (!userBehavior) return this.userProfiles.newbie;

        const { orderHistory, clickHistory, preferences } = userBehavior;
        
        // 分析用户行为特征
        const traits = this.analyzeUserTraits(userBehavior);
        
        // 根据特征匹配用户画像
        if (traits.healthScore > 0.7) return this.userProfiles.health_conscious;
        if (traits.adventureScore > 0.7) return this.userProfiles.adventurous;
        if (traits.budgetScore > 0.7) return this.userProfiles.budget_conscious;
        if (traits.foodieScore > 0.7) return this.userProfiles.foodie;
        
        return this.userProfiles.newbie;
    }

    // 分析用户特征
    analyzeUserTraits(userBehavior) {
        const { orderHistory, clickHistory } = userBehavior;
        
        let healthScore = 0;
        let adventureScore = 0;
        let budgetScore = 0;
        let foodieScore = 0;
        
        // 分析订单历史
        orderHistory.forEach(order => {
            order.dishes.forEach(dish => {
                // 健康特征分析
                if (dish.tags.includes('健康') || dish.tags.includes('素食')) {
                    healthScore += 0.1;
                }
                
                // 冒险特征分析
                if (dish.tags.includes('辣') || dish.tags.includes('异国')) {
                    adventureScore += 0.1;
                }
                
                // 经济特征分析
                if (dish.price < 20) {
                    budgetScore += 0.1;
                }
                
                // 美食家特征分析
                if (dish.tags.includes('招牌') || dish.tags.includes('特色')) {
                    foodieScore += 0.1;
                }
            });
        });
        
        return {
            healthScore: Math.min(healthScore, 1),
            adventureScore: Math.min(adventureScore, 1),
            budgetScore: Math.min(budgetScore, 1),
            foodieScore: Math.min(foodieScore, 1)
        };
    }

    // 生成个性化推荐理由
    generatePersonalizedReason(dish, userProfile, context) {
        const { timeInfo, weatherInfo } = context;
        const reasons = [];
        
        // 时间相关理由
        const timeReasons = this.reasonTemplates.time[timeInfo.timeOfDay] || [];
        if (timeReasons.length > 0) {
            reasons.push(timeReasons[Math.floor(Math.random() * timeReasons.length)]);
        }
        
        // 天气相关理由
        const weatherReasons = this.reasonTemplates.weather[weatherInfo.condition] || [];
        if (weatherReasons.length > 0) {
            reasons.push(weatherReasons[Math.floor(Math.random() * weatherReasons.length)]);
        }
        
        // 季节相关理由
        const seasonReasons = this.reasonTemplates.season[timeInfo.season] || [];
        if (seasonReasons.length > 0) {
            reasons.push(seasonReasons[Math.floor(Math.random() * seasonReasons.length)]);
        }
        
        // 用户偏好相关理由
        if (userProfile.preferences.includes('healthy') && dish.tags.includes('健康')) {
            const healthReasons = this.reasonTemplates.preference.healthy;
            reasons.push(healthReasons[Math.floor(Math.random() * healthReasons.length)]);
        }
        
        if (userProfile.preferences.includes('spicy') && dish.tags.includes('辣')) {
            const spicyReasons = this.reasonTemplates.preference.spicy;
            reasons.push(spicyReasons[Math.floor(Math.random() * spicyReasons.length)]);
        }
        
        // 菜品特色理由
        if (dish.isHotSeller) {
            const popularReasons = this.reasonTemplates.dish.popular;
            reasons.push(popularReasons[Math.floor(Math.random() * popularReasons.length)]);
        }
        
        if (dish.hasDiscount) {
            const discountReasons = this.reasonTemplates.dish.discount;
            reasons.push(discountReasons[Math.floor(Math.random() * discountReasons.length)]);
        }
        
        if (dish.rating > 4.5) {
            const ratingReasons = this.reasonTemplates.dish.high_rating;
            reasons.push(ratingReasons[Math.floor(Math.random() * ratingReasons.length)]);
        }
        
        // 组合推荐理由
        if (reasons.length === 0) {
            return "🍽️ 为您精心推荐这道美味菜品";
        }
        
        // 随机选择1-2个理由组合
        const selectedReasons = this.shuffleArray(reasons).slice(0, Math.min(2, reasons.length));
        return selectedReasons.join(' ');
    }

    // 生成AI对话式推荐
    generateAIConversation(userId, recommendations, context) {
        const userProfile = this.getUserProfile(userId);
        const { timeInfo, weatherInfo } = context;
        
        const greetings = [
            `👋 您好！我是${this.aiPersonality.name}，您的专属美食推荐助手`,
            `🍽️ 欢迎回来！让我为您推荐今天的美食`,
            `😊 很高兴为您服务，今天想吃什么？`,
            `🎯 根据您的喜好，我为您精心挑选了这些美食`
        ];
        
        const contextMessages = [
            `现在${this.getTimeDescription(timeInfo.timeOfDay)}，${this.getWeatherDescription(weatherInfo.condition)}`,
            `考虑到${this.getSeasonDescription(timeInfo.season)}的特点`,
            `结合您${userProfile.name}的偏好`,
            `为您推荐${recommendations.length}道精选菜品`
        ];
        
        const encouragements = [
            "希望您用餐愉快！",
            "祝您用餐愉快，心情美好！",
            "期待您的反馈，我会继续优化推荐！",
            "如有任何问题，随时告诉我！"
        ];
        
        const greeting = greetings[Math.floor(Math.random() * greetings.length)];
        const contextMessage = contextMessages[Math.floor(Math.random() * contextMessages.length)];
        const encouragement = encouragements[Math.floor(Math.random() * encouragements.length)];
        
        return {
            greeting: greeting,
            context: contextMessage,
            encouragement: encouragement,
            totalRecommendations: recommendations.length
        };
    }

    // 获取时间描述
    getTimeDescription(timeOfDay) {
        const descriptions = {
            'morning': '早上时光',
            'lunch': '午餐时间',
            'afternoon': '下午时光',
            'dinner': '晚餐时间',
            'night': '夜宵时间'
        };
        return descriptions[timeOfDay] || '这个时间';
    }

    // 获取天气描述
    getWeatherDescription(condition) {
        const descriptions = {
            'sunny': '阳光明媚',
            'rainy': '雨天湿润',
            'cloudy': '多云天气',
            'hot': '天气炎热',
            'cold': '天气寒冷'
        };
        return descriptions[condition] || '天气不错';
    }

    // 获取季节描述
    getSeasonDescription(season) {
        const descriptions = {
            'spring': '春季',
            'summer': '夏季',
            'autumn': '秋季',
            'winter': '冬季'
        };
        return descriptions[season] || '这个季节';
    }

    // 生成智能推荐
    async generateRecommendations(userId, limit = 10) {
        try {
            // 获取上下文信息
            const timeInfo = this.getCurrentTimeInfo();
            const weatherInfo = await this.getWeatherInfo();
            const userProfile = this.getUserProfile(userId);
            
            // 获取所有菜品
            const allDishes = this.db.getDishes();
            if (allDishes.length === 0) {
                return {
                    recommendations: [],
                    context: { timeInfo, weatherInfo },
                    conversation: null
                };
            }
            
            // 计算推荐分数
            const scoredDishes = allDishes.map(dish => {
                const score = this.calculateEnhancedScore(dish, userProfile, timeInfo, weatherInfo);
                return {
                    ...dish,
                    recommendationScore: score.total,
                    recommendationReason: this.generatePersonalizedReason(dish, userProfile, { timeInfo, weatherInfo }),
                    scoreBreakdown: score.breakdown
                };
            });
            
            // 排序并选择推荐
            const recommendations = scoredDishes
                .sort((a, b) => b.recommendationScore - a.recommendationScore)
                .slice(0, limit);
            
            // 生成AI对话
            const conversation = this.generateAIConversation(userId, recommendations, { timeInfo, weatherInfo });
            
            // 记录推荐历史
            this.recordRecommendationHistory(userId, recommendations);
            
            return {
                recommendations: recommendations,
                context: { timeInfo, weatherInfo },
                conversation: conversation
            };
            
        } catch (error) {
            console.error('AI推荐生成失败:', error);
            return {
                recommendations: [],
                context: null,
                conversation: null
            };
        }
    }

    // 增强版评分算法
    calculateEnhancedScore(dish, userProfile, timeInfo, weatherInfo) {
        let totalScore = 0;
        const breakdown = {};
        
        // 基础分数
        const baseScore = 50;
        totalScore += baseScore;
        breakdown.base = baseScore;
        
        // 时间匹配分数
        const timeScore = this.getTimeScore(dish, timeInfo);
        totalScore += timeScore;
        breakdown.time = timeScore;
        
        // 天气匹配分数
        const weatherScore = this.getWeatherScore(dish, weatherInfo);
        totalScore += weatherScore;
        breakdown.weather = weatherScore;
        
        // 季节匹配分数
        const seasonScore = this.getSeasonScore(dish, timeInfo.season);
        totalScore += seasonScore;
        breakdown.season = seasonScore;
        
        // 用户偏好分数
        const preferenceScore = this.getPreferenceScore(dish, userProfile);
        totalScore += preferenceScore;
        breakdown.preference = preferenceScore;
        
        // 菜品特色分数
        const dishScore = this.getDishFeatureScore(dish);
        totalScore += dishScore;
        breakdown.dish = dishScore;
        
        // 随机性分数（增加推荐多样性）
        const randomScore = Math.random() * 10;
        totalScore += randomScore;
        breakdown.random = randomScore;
        
        return {
            total: Math.max(0, Math.min(100, totalScore)),
            breakdown: breakdown
        };
    }

    // 获取菜品特色分数
    getDishFeatureScore(dish) {
        let score = 0;
        
        if (dish.isHotSeller) score += 15;
        if (dish.hasDiscount) score += 10;
        if (dish.rating > 4.5) score += 20;
        if (dish.rating > 4.0) score += 10;
        if (dish.sales > 100) score += 10;
        if (dish.stock < 10) score += 5; // 稀缺性加分
        
        return score;
    }

    // 获取时间分数
    getTimeScore(dish, timeInfo) {
        const timePreferences = {
            'morning': ['粥', '包子', '豆浆', '面条', '早餐', '清淡'],
            'lunch': ['米饭', '面条', '快餐', '套餐', '主食', '营养'],
            'afternoon': ['茶点', '甜品', '小食', '饮品', '轻食'],
            'dinner': ['正餐', '火锅', '烧烤', '大菜', '丰盛'],
            'night': ['夜宵', '烧烤', '小吃', '饮品', '小食']
        };

        const preferredKeywords = timePreferences[timeInfo.timeOfDay] || [];
        const description = dish.description.toLowerCase();
        const name = dish.name.toLowerCase();
        const category = dish.category.toLowerCase();

        let matchCount = 0;
        preferredKeywords.forEach(keyword => {
            if (description.includes(keyword) || name.includes(keyword) || category.includes(keyword)) {
                matchCount++;
            }
        });

        return matchCount * 8;
    }

    // 获取天气分数
    getWeatherScore(dish, weatherInfo) {
        const weatherPreferences = {
            'sunny': ['清爽', '凉菜', '沙拉', '冷饮', '水果', '清淡'],
            'rainy': ['热汤', '火锅', '热饮', '暖身', '温暖'],
            'cloudy': ['家常', '经典', '传统', '温和'],
            'hot': ['清凉', '冷饮', '沙拉', '水果', '解暑', '冰镇'],
            'cold': ['热食', '火锅', '热汤', '暖胃', '温补']
        };

        const preferredKeywords = weatherPreferences[weatherInfo.condition] || [];
        const description = dish.description.toLowerCase();
        const name = dish.name.toLowerCase();

        let matchCount = 0;
        preferredKeywords.forEach(keyword => {
            if (description.includes(keyword) || name.includes(keyword)) {
                matchCount++;
            }
        });

        return matchCount * 10;
    }

    // 获取季节分数
    getSeasonScore(dish, season) {
        const seasonPreferences = {
            'spring': ['清淡', '新鲜', '蔬菜', '春菜', '清爽'],
            'summer': ['清凉', '解暑', '冷饮', '沙拉', '清爽'],
            'autumn': ['温补', '润燥', '秋菜', '养生', '滋润'],
            'winter': ['温补', '暖身', '热食', '进补', '温暖']
        };

        const preferredKeywords = seasonPreferences[season] || [];
        const description = dish.description.toLowerCase();
        const name = dish.name.toLowerCase();

        let matchCount = 0;
        preferredKeywords.forEach(keyword => {
            if (description.includes(keyword) || name.includes(keyword)) {
                matchCount++;
            }
        });

        return matchCount * 8;
    }

    // 获取偏好分数
    getPreferenceScore(dish, userProfile) {
        let score = 0;
        
        // 根据用户画像调整分数
        if (userProfile.preferences.includes('healthy') && dish.tags.includes('健康')) {
            score += 20;
        }
        
        if (userProfile.preferences.includes('spicy') && dish.tags.includes('辣')) {
            score += 15;
        }
        
        if (userProfile.preferences.includes('budget') && dish.price < 30) {
            score += 10;
        }
        
        if (userProfile.preferences.includes('innovative') && dish.tags.includes('特色')) {
            score += 15;
        }
        
        return score;
    }

    // 获取当前时间信息
    getCurrentTimeInfo() {
        const now = new Date();
        const hour = now.getHours();
        const dayOfWeek = now.getDay();
        const month = now.getMonth() + 1;
        
        return {
            hour: hour,
            dayOfWeek: dayOfWeek,
            month: month,
            season: this.getSeason(month),
            timeOfDay: this.getTimeOfDay(hour),
            isWeekend: dayOfWeek === 0 || dayOfWeek === 6
        };
    }

    // 获取季节
    getSeason(month) {
        if (month >= 3 && month <= 5) return 'spring';
        if (month >= 6 && month <= 8) return 'summer';
        if (month >= 9 && month <= 11) return 'autumn';
        return 'winter';
    }

    // 获取时段
    getTimeOfDay(hour) {
        if (hour >= 6 && hour < 10) return 'morning';
        if (hour >= 10 && hour < 14) return 'lunch';
        if (hour >= 14 && hour < 17) return 'afternoon';
        if (hour >= 17 && hour < 21) return 'dinner';
        if (hour >= 21 || hour < 6) return 'night';
        return 'unknown';
    }

    // 获取天气信息
    async getWeatherInfo() {
        // 检查缓存
        if (this.weatherCache && this.weatherCacheTime && 
            (Date.now() - this.weatherCacheTime) < this.weatherCacheDuration) {
            return this.weatherCache;
        }
        
        // 模拟天气数据
        const weatherConditions = [
            { condition: 'sunny', temperature: 25, humidity: 60 },
            { condition: 'rainy', temperature: 18, humidity: 85 },
            { condition: 'cloudy', temperature: 22, humidity: 70 },
            { condition: 'hot', temperature: 35, humidity: 50 },
            { condition: 'cold', temperature: 5, humidity: 90 }
        ];
        
        const randomWeather = weatherConditions[Math.floor(Math.random() * weatherConditions.length)];
        
        this.weatherCache = {
            condition: randomWeather.condition,
            temperature: randomWeather.temperature,
            humidity: randomWeather.humidity,
            description: this.getWeatherDescription(randomWeather.condition)
        };
        
        this.weatherCacheTime = Date.now();
        
        return this.weatherCache;
    }

    // 获取天气描述
    getWeatherDescription(condition) {
        const descriptions = {
            'sunny': '阳光明媚',
            'rainy': '雨天湿润',
            'cloudy': '多云天气',
            'hot': '天气炎热',
            'cold': '天气寒冷'
        };
        return descriptions[condition] || '天气不错';
    }

    // 记录推荐历史
    recordRecommendationHistory(userId, recommendations) {
        const history = this.getRecommendationHistory(userId);
        history.push({
            timestamp: new Date().toISOString(),
            recommendations: recommendations.map(r => ({
                id: r.id,
                name: r.name,
                score: r.recommendationScore
            }))
        });
        
        // 只保留最近50条记录
        if (history.length > 50) {
            history.splice(0, history.length - 50);
        }
        
        localStorage.setItem(`recommendationHistory_${userId}`, JSON.stringify(history));
    }

    // 获取推荐历史
    getRecommendationHistory(userId) {
        const history = localStorage.getItem(`recommendationHistory_${userId}`);
        return history ? JSON.parse(history) : [];
    }

    // 获取用户行为
    getUserBehavior(userId) {
        const behavior = localStorage.getItem(`userBehavior_${userId}`);
        return behavior ? JSON.parse(behavior) : null;
    }

    // 加载用户行为
    loadUserBehavior() {
        const behavior = localStorage.getItem('userBehavior');
        return behavior ? JSON.parse(behavior) : {};
    }

    // 加载推荐历史
    loadRecommendationHistory() {
        const history = localStorage.getItem('recommendationHistory');
        return history ? JSON.parse(history) : {};
    }

    // 学习用户行为
    learnFromUserBehavior(userId, action, data) {
        let behavior = this.getUserBehavior(userId) || {
            orderHistory: [],
            clickHistory: [],
            preferences: {}
        };
        
        switch (action) {
            case 'click':
                behavior.clickHistory.push({
                    dishId: data.dishId,
                    timestamp: new Date().toISOString(),
                    context: data.context
                });
                break;
                
            case 'order':
                behavior.orderHistory.push({
                    dishes: data.dishes,
                    timestamp: new Date().toISOString(),
                    context: data.context
                });
                break;
                
            case 'preference':
                behavior.preferences = { ...behavior.preferences, ...data };
                break;
        }
        
        // 只保留最近100条记录
        if (behavior.clickHistory.length > 100) {
            behavior.clickHistory.splice(0, behavior.clickHistory.length - 100);
        }
        if (behavior.orderHistory.length > 100) {
            behavior.orderHistory.splice(0, behavior.orderHistory.length - 100);
        }
        
        localStorage.setItem(`userBehavior_${userId}`, JSON.stringify(behavior));
    }

    // 工具函数：数组洗牌
    shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }
}

// 创建全局实例
window.enhancedAIRecommendationEngine = new EnhancedAIRecommendationEngine();
